﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ProjectileManager : MonoBehaviour {

    private static ProjectileManager instance;
    public static ProjectileManager Instance
    {
        get { return instance; }
    }



    public GameObject[] ProjectilePrefabList;

    public Queue<Projectile> ProjectilePool = new Queue<Projectile>();

    private void Awake()
    {
        if(instance==null)instance = this;
        else if(instance!=this)
        {
            Destroy(this);
            return;
        }
        
    }

    public void Return2Pool(GameObject obj)
    {
        obj.SetActive(false);
    }


    public Projectile InstantiateProjectile(Vector3 origin,Quaternion rotation,ProjectileType projectileType)
    {
        Projectile ob = null;

        foreach (var pobj in ProjectilePrefabList)
        {
            if (pobj.GetComponent<Projectile>().type == projectileType)
            {
                Projectile p = pobj.GetComponent<Projectile>();
                if (ProjectilePool.Count == 0)
                {
                    ob = Instantiate(pobj, origin, rotation).GetComponent<Projectile>();
                    ob.origin = origin;
                    break;
                }
                else
                {
                    ob = ProjectilePool.Dequeue();
                    ob.gameObject.SetActive(true);
                    ob.transform.position = origin;
                    ob.origin = origin;
                    ob.transform.rotation = rotation;
                    p.CloneTo(ref ob);
                }
            }
        }

        return ob;
    }
}
